package com.winit.openapi.cwm.csi.controller;

import com.alibaba.fastjson.JSON;
import com.winit.common.spi.context.CommandContext;
import com.winit.cwm.spi.common.exception.CWMException;
import com.winit.cwm.spi.csi.InboundPackageService;
import com.winit.cwm.spi.csi.command.BatchPrintPackageLabelCommand;
import com.winit.cwm.spi.csi.command.ImportInboundPackageCommand;
import com.winit.cwm.spi.csi.vo.AddPackageMerchandiseVo;
import com.winit.cwm.spi.csi.vo.AddPackageVo;
import com.winit.cwm.spi.csi.vo.PackageLabelVo;
import com.winit.cwm.spi.csi.vo.PrintPackageLabelBatchForApiReturnVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.PDFBox4MergePDF;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 自验货对外API接口
 * Created by mengzheng.tang on 2017/10/11.
 */

@Controller
@RequestMapping(value = "/winit/csi")
public class CsiApiController extends BaseController {

    @Resource
    private InboundPackageService inspectPackageService;

    /**ums客户信息 */
    @Resource
    private UmsCustomerService umsCustomerService;

    /**
     * 批量打印包裹条码
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchPrintPackageLabel")
    public String batchPrintPackageLabel (@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        BatchPrintPackageLabelCommand command = JSON.parseObject(requestMsg.getData().toString(), BatchPrintPackageLabelCommand.class);

        List<String> packageCodes = new ArrayList<String>();
        List<PackageLabelVo> packageLabelVos = command.getPackageList();
        for(PackageLabelVo packageLabelVo : packageLabelVos) {
            if (StringUtils.isBlank(packageLabelVo.getPackageSerno())) {
                throw new CWMException(ErrorCode.FIELD_NOT_NULL, "packageSerno");
            }
            packageCodes.add(packageLabelVo.getPackageSerno());
        }

        List<String> bytes = inspectPackageService.printPackageLabelBatch(command);

        PDFBox4MergePDF tool = new PDFBox4MergePDF();
        ByteArrayOutputStream out=new ByteArrayOutputStream();

        try {
            List<byte []> byteList= tool.decryptBASE64(bytes);
            tool.merge(byteList, out);
        } catch (IOException e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        String mergeByte= tool.base64Encode(out.toByteArray());

        PrintPackageLabelBatchForApiReturnVo returnVo = new PrintPackageLabelBatchForApiReturnVo();
        if (mergeByte!=null && mergeByte.length()>0) {
            returnVo.setFiles(mergeByte);
            returnVo.setPackageCodes(packageCodes);
        }
        responseMsg.setData(returnVo);

        return SUCCESS;
    }

    /**
     * 批量新增包裹
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addInspectionPackage")
    public String addInspectionPackage(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ImportInboundPackageCommand command = JSON.parseObject(requestMsg.getData().toString(), ImportInboundPackageCommand.class);

        List<AddPackageVo> addPackageVos = command.getAddPackageVos();
        for (AddPackageVo addPackageVo : addPackageVos) {
            this.validatePackage(addPackageVo);
        }

        command.setCustomerCode(this.getContextCustomer().getCode());
        //返回包裹条码列表
        List<String> packageSernos = inspectPackageService.importInboundPackage(command);
        responseMsg.setData(packageSernos);
        return SUCCESS;
    }

    private CustomerInfoVO getContextCustomer() {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        return customer;
    }

    /**
     * 校验新增包裹参数
     * @param addPackageVo
     */
    private void validatePackage(AddPackageVo addPackageVo) {
        //箱单号不能超过32位
        if (addPackageVo.getCaseNo().length() > 32) {
            throw new ApiException(ErrorCode.FIELD_LENGTH_TO_LONG, "CaseNo", "32");
        }

        //长宽高不能超过两位小数，重量不能超过4位
        if (addPackageVo.getEstimateLength().scale() > 2
                || addPackageVo.getEstimateWidth().scale() > 2
                || addPackageVo.getEstimateHeight().scale() > 2) {
            throw new ApiException(ErrorCode.FIELD_LENGTH_TO_LONG, "size", "2");
        }

        if (addPackageVo.getEstimateWeight().scale() > 4) {
            throw new ApiException(ErrorCode.FIELD_LENGTH_TO_LONG, "weight", "4");
        }

        //预计单品数不能小于等于0
        for (AddPackageMerchandiseVo addPackageMerchandiseVo : addPackageVo.getMerchandiseList()) {
            if (addPackageMerchandiseVo != null ) {
                if (addPackageMerchandiseVo.getEstimateItemQty() <= 0) {
                    throw new ApiException(ErrorCode.FIELD_MUST_BE_BIGGER_THAN_ZERO, "estimateItemQty");
                }
            }
        }
    }
}
